package com.top.ruizhong.main.video

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.MediaMetadataRetriever
import android.text.Editable
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.hw.videoprocessor.VideoProcessor
import com.module.lemlin.base.loadCropImage
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.top.ruizhong.R
import com.top.ruizhong.entity.UploadResponse
import com.top.ruizhong.entity.VideoDraft
import com.top.ruizhong.main.host.MainActivity
import com.top.ruizhong.mode.manager.getDiskCacheDirectoryVideo
import com.top.ruizhong.mode.vm.VideoViewModel
import com.top.ruizhong.popup.ProgressPopup
import com.top.ruizhong.popup.VideoPickerPopup
import com.top.ruizhong.util.LocationUtils
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import kotlinx.android.synthetic.main.activity_video_keep.*
import java.io.File
import java.lang.Exception


class VideoKeepActivity : ViewModeActivity<VideoViewModel>() {

    companion object {

        private const val EXTRA_KEY_VIDEO_PATH = "EXTRA_KEY_VIDEO_PATH"
        private const val EXTRA_KEY_BITMAP_PATH = "EXTRA_KEY_BITMAP_PATH"
        private const val EXTRA_KEY_VIDEO_ACTION = "EXTRA_KEY_VIDEO_ACTION"
        private const val EXTRA_KEY_VIDEO_DRAFT = "EXTRA_KEY_VIDEO_DRAFT"

        private const val EDIT_YES = 1
        private const val EDIT_NOT = 2

        fun openEditYes(activity: Activity, pathVideo: String, pathBitmap: String) {
            val intent = Intent(activity, VideoKeepActivity::class.java)
            intent.putExtra(EXTRA_KEY_VIDEO_PATH, pathVideo)
            intent.putExtra(EXTRA_KEY_BITMAP_PATH, pathBitmap)
            intent.putExtra(EXTRA_KEY_VIDEO_ACTION, EDIT_YES)
            activity.startActivity(intent)
        }

        fun openEditNot(activity: Activity, videoDraft: VideoDraft) {
            val intent = Intent(activity, VideoKeepActivity::class.java)
            intent.putExtra(EXTRA_KEY_VIDEO_ACTION, EDIT_NOT)
            intent.putExtra(EXTRA_KEY_VIDEO_DRAFT, videoDraft)
            activity.startActivity(intent)
        }

        private val videoType: MutableList<Picker> =
            mutableListOf(Picker(type = 1, name = "普通视频"), Picker(type = 2, name = "广告视频"))

        private val videoDraft: MutableList<Picker> =
            mutableListOf(Picker(type = 2, name = "视频草稿箱"), Picker(type = 3, name = "私人草稿箱"))

        data class Picker(val type: Int, val name: String)
    }

    private val mVideoAddRequest: VideoAddRequest = VideoAddRequest()

    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = this, onConfirm = {
            mProgressPopup.dismiss()
            MainActivity.open(activity = this)
        }, onCancel = {
            mProgressPopup.dismiss()
            viewModel.dispose.clear()
        })
    }

    private val mVideoPickerPopup: VideoPickerPopup by lazy {
        VideoPickerPopup(context = this, onConfirm = { action, position ->
            if (action == null)
                return@VideoPickerPopup
            if (action == VideoPickerPopup.Action.PICKER_VIDEO_KIND) {
                viewModel.videoCateTotalListLiveData.value?.httpData?.data?.let {
                    mVideoAddRequest.cate_id = it[position].id
                    tvVideoEditCate.text = it[position].name
                }
            } else if (action == VideoPickerPopup.Action.PICKER_VIDEO_TYPE) {
                val type: Int = videoType[position].type

                mVideoAddRequest.type = type
                tvVideoEditType.text = videoType[position].name

                if (type == 1) {
                    ivVideoEditImageLink.setImageResource(R.mipmap.ic_17630)
                    etVideoEditTitleLink.text = null
                    mVideoAddRequest.adv_image = null
                    mVideoAddRequest.adv_title = null
                    clVideoEditLink.visibility = View.GONE
                } else {
                    clVideoEditLink.visibility = View.VISIBLE
                }

            } else if (action == VideoPickerPopup.Action.PICKER_VIDEO_DRAFT) {
                validationFormUpload(act = videoDraft[position].type)
            }
        })
    }

    //视频链接图片地址
    private var pathLink: String? = null

    //视频第一帧图片地址
    private var pathBitmap: String? = null

    //视频文件地址
    private var pathVideo: String? = null

    override val layoutResId: Int
        get() = R.layout.activity_video_keep

    override fun viewModel(): VideoViewModel {
        return createViewModel()
    }

    override fun stateBar(): StatusBar =
        StatusBar(view = flVideoEditBar)

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            ivVideoEditImageLink.loadRoundImage(
                pathList[0].apply { pathLink = this },
                radius = ConvertUtils.dp2px((10f))
            )
        }
    }

    override fun initView() {

        pathBitmap = intent?.getStringExtra(EXTRA_KEY_BITMAP_PATH)
        pathVideo = intent?.getStringExtra(EXTRA_KEY_VIDEO_PATH)

        initFillView()

        ivVideoEditBack.setOnClickListener {
            finish()
        }

        //视频分类
        tvVideoEditCate.setOnClickListener {
            viewModel.videoCateTotalList()
        }
        //视频类型
        tvVideoEditType.setOnClickListener {
            val data: MutableList<String> = mutableListOf()
            videoType.forEach { data.add(it.name) }
            mVideoPickerPopup.setFillData(
                title = "请选择视频类型", pickers = data
            ).setAction(VideoPickerPopup.Action.PICKER_VIDEO_TYPE)
                .showPopupWindow()
        }

        //链接图片选择
        ivVideoEditImageLink.setOnClickListener {
            Matisse.from(this)
                .choose(MimeType.ofImage()) //图片类型
                .countable(true) //true:选中后显示数字;false:选中后显示对号
                .maxSelectable(1) //可选的最大数
                .imageEngine(GlideEngine()) //图片加载引擎
                .theme(R.style.Matisse_Zhihu1)
                .forResult(100) //
        }

        //直接上传
        tvVideoEditUpload.setOnClickListener {
            validationFormUpload(act = 1)
        }
        //保存草稿箱
        tvVideoEditBoxDraft.setOnClickListener {
            val data: MutableList<String> = mutableListOf()
            videoDraft.forEach { data.add(it.name) }
            mVideoPickerPopup.setFillData(
                title = "请选择草稿箱", pickers = data
            ).setAction(VideoPickerPopup.Action.PICKER_VIDEO_DRAFT)
                .showPopupWindow()


//            Thread{
//                try {
//                    pathVideo?.let {
//                        val mmr = MediaMetadataRetriever()
//                        mmr.setDataSource(it)
//                        val originWidth: Int =
//                            mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
//                                ?.toInt() ?: return@let
//                        val originHeight: Int =
//                            mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
//                                ?.toInt() ?: return@let
//                        val bitrate: Int =
//                            mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)
//                                ?.toInt() ?: return@let
//                        LogUtils.e("=====${originWidth}===${originHeight}===${bitrate}")
//                        val file = File(
//                            getDiskCacheDirectoryVideo(this as Context).path,
//                            ("${System.currentTimeMillis()}.mp4")
//                        )
//                        file.createNewFile()
//                        VideoProcessor.processor(this)
//                            .input(it)
//                            .bitrate(bitrate / 2)
//                            .output(
//                                file.path
//                            ).progressListener { progress->
//                                LogUtils.e("===${progress}")
//                            }.process()
//                    }
//                }catch (e:Exception){
//                    LogUtils.e("Exception===${e.message}")
//                }
//            }.start()

        }
        //发布
        tvVideoEditRelease.setOnClickListener {

        }
        //保存
        tvVideoEditSave.setOnClickListener {

        }

        //视频标题输入监听
        etVideoEditTitle.addTextChangedListener {
            mVideoAddRequest.title = it?.toString()
        }
        //视频描述输入监听
        etVideoEditDesc.addTextChangedListener {
            mVideoAddRequest.description = it?.toString()
        }
        //链接标题输入监听
        etVideoEditTitleLink.addTextChangedListener {
            mVideoAddRequest.adv_title = it?.toString()
        }

    }

    override fun initData() {

    }

    override fun initViewMode() {

        viewModel.videoCateTotalListLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> {
                    mVideoPickerPopup.setAction(VideoPickerPopup.Action.PICKER_VIDEO_KIND)
                        .showPopupWindow()
                }
                Status.FAILURE -> {
                    mVideoPickerPopup.dismiss()
                    toast(response.throwable?.msg ?: "未知错误")
                }
                Status.SUCCESS -> response.httpData?.data?.let { videoCate ->
                    val data: MutableList<String> = mutableListOf()
                    videoCate.forEach { data.add(it.name) }
                    mVideoPickerPopup.setFillData(
                        title = "请选择视频分类", pickers = data
                    )
                }
            }
        })

        viewModel.uploadLiveData.observe(this as LifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> {
                    if (!mProgressPopup.isShowing)
                        mProgressPopup.showPopupWindow()
                    mProgressPopup.resetProgress()
                }
                Status.FAILURE -> {
                    mProgressPopup.dismiss()
                    toast(response.throwable?.msg ?: "未知错误")
                }
                else -> response.httpData?.let {
                    when (it.type) {
                        UploadResponse.Type.FILE_IMAGE_AD -> pathBitmap?.let { path ->
                            mVideoAddRequest.adv_image = it.data.url
                            viewModel.commonUpload(path, UploadResponse.Type.FILE_IMAGE_FRAME)
                        }
                        UploadResponse.Type.FILE_IMAGE_FRAME -> pathVideo?.let { path ->
                            mVideoAddRequest.main_image = it.data.url
                            viewModel.commonUpload(path, UploadResponse.Type.FILE_VIDEO)
                        }
                        else -> {
                            mVideoAddRequest.path = it.data.url
                            mProgressPopup.dismiss()
                            //viewModel.videoAdd(mVideoAddRequest)
                            LogUtils.e(GsonUtils.toJson(mVideoAddRequest))
                        }
                    }
                }
            }
        })

        viewModel.progressLiveData.observe(this as LifecycleOwner, Observer { progress ->
            mProgressPopup.setProgress(progress)
        })
//
//        viewModel.audioAddLiveData.observe(this as LifecycleOwner, Observer { response ->
//            if (response.status == Status.FAILURE) {
//                mProgressPopup.dismiss()
//                toast(response.throwable?.msg ?: "未知错误")
//            }
//            if (response.status == Status.SUCCESS) {
//                mProgressPopup.setMessage("视频已上传")
//                intent?.getStringExtra(EXTRA_KEY_VIDEO_PATH)?.let { path ->
//                    FileUtils.delete(path)
//                }
//            }
//        })
    }


    private fun initFillView() {
        val action: Int = intent?.getIntExtra(EXTRA_KEY_VIDEO_ACTION, EDIT_YES)
            ?: return

        intent?.getStringExtra(EXTRA_KEY_BITMAP_PATH)?.let {
            ivVideoEditImageFrame.loadRoundImage(it, radius = ConvertUtils.dp2px(10f))
        }

        llVideoEditYes.visibility =
            if (action == EDIT_YES) View.VISIBLE else View.INVISIBLE
        llVideoEditNot.visibility =
            if (action == EDIT_NOT) View.VISIBLE else View.INVISIBLE
//        clVideoEditLink.visibility =
//            if (RZApplication.userInfo()?.is_certified_merchant == 1) View.VISIBLE else View.GONE
    }

    private fun setFillDataEditNot() {
        llVideoEditYes.visibility = View.INVISIBLE
        llVideoEditNot.visibility = View.VISIBLE

        val videoDraft: VideoDraft =
            intent?.getSerializableExtra(EXTRA_KEY_VIDEO_DRAFT) as? VideoDraft ?: return



    }


    private fun validationFormUpload(act: Int) {

        mVideoAddRequest.act = act.toString()

        val string: String? = if (mVideoAddRequest.cate_id == 0) {
            "请选择视频分类"
        } else if (mVideoAddRequest.title.isNullOrEmpty()) {
            "请输入视频标题"
        } else if (mVideoAddRequest.description.isNullOrEmpty()) {
            "请输入视频描述"
        } else if (mVideoAddRequest.type == 0) {
            "请选择视频类型"
        } else if (mVideoAddRequest.type == 2 && mVideoAddRequest.adv_title.isNullOrEmpty()) {
            "请输入链接标题"
        } else if (mVideoAddRequest.type == 2 && pathLink.isNullOrEmpty()) {
            "请选择链接图片"
        } else if (pathBitmap.isNullOrEmpty()) {
            "视频第一帧图片地址为空，请查看相关代码！"
        } else if (pathVideo.isNullOrEmpty()) {
            "视频地址为空，请查看相关代码"
        } else null

        if (!string.isNullOrEmpty()) {
            toast(string)
            return
        }



        if (mVideoAddRequest.type == 2) pathLink?.let {
            viewModel.commonUpload(it, UploadResponse.Type.FILE_IMAGE_AD)
        } else if (mVideoAddRequest.type == 1) pathBitmap?.let {
            viewModel.commonUpload(it, UploadResponse.Type.FILE_IMAGE_FRAME)
        }
    }

    private fun validationFormSave() {

    }

    private fun validationFormRelease() {

    }

    class VideoAddRequest {
        var cate_id: Int = 0//分类
        var title: String? = null//标题
        var description: String? = null//描述
        var main_image: String? = null//视频第一帧图片 相对路径
        var path: String? = null//上传返回的地址 相对路径
        var province: String = "福建省"//省（同城要用到）
        var city: String = "福州市"//市 （同城要用到）
        var type: Int = 0//类型：1普通2广告（广告权限使用用户信息的is_certified_merchant字段判断）
        var act: String? = null//操作：1上传审核2存入草稿箱3私人草稿箱
        var adv_title: String? = null//广告标题（type是2的时候必传）
        var adv_image: String? = null//广告图片（type是2的时候必传）
    }

}